<script setup lang="ts">
import {ref, onMounted} from "vue";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import Banner from "@/components/MyComponents/Banner.vue";
import {getDocContractByUserId} from "@/api/contractHomepage/docContractHome";
import { addDocOrder } from "@/api/orderManagement/docOrder";

const router = useRouter();

// 设置导航标题
const bannerTitle = ref("待签约团队");

// 搜索处理函数
const handleBannerSearch = (keyword: string) => {
  console.log("搜索关键词:", keyword);
};

// 分页参数
const queryParams = ref({pageNum: 1, pageSize: 10});
const total = ref(0);
const pendingTeams = ref<any[]>([]);

// 加载数据
const loadData = async () => {
  try {
    const res = await getDocContractByUserId(queryParams.value);
    if (res.code === 200) {
      pendingTeams.value = res.rows || [];
      total.value = res.total || 0;
    } else {
      ElMessage.error(res.msg || "获取数据失败");
    }
  } catch (e) {
    ElMessage.error("接口调用失败");
  }
};

// 分页事件
const handlePageChange = (newPage: number) => {
  queryParams.value.pageNum = newPage;
  loadData();
};

const handleSizeChange = (newSize: number) => {
  queryParams.value.pageSize = newSize;
  queryParams.value.pageNum = 1;
  loadData();
};

// 处理签约操作
const handleSign = (team: any) => {
  ElMessage.success(`已发起签约：${team.teamName}`);
  // 获取当前待签约记录的ID
  const orderId = team.orderId;
  console.log("订单ID:", orderId);
  // 创建订单数据
  const orderData = {
    orderPrice: team.teamPrice * team.contractDuration,
    orderId:orderId
  };

  // 调用API创建订单
  addDocOrder(orderData).then(response => {
    if (response.code === 200) {
      ElMessage.success(`已发起签约：${team.teamName}，订单创建成功`);

      // 刷新本页面
      window.location.reload();
    } else {
      ElMessage.error(response.msg || "订单创建失败");
    }
  }).catch(error => {
    console.error("订单创建失败:", error);
    ElMessage.error("订单创建失败");
  });
};

// 跳转到订单页面
const goToOrderPage = (team: any) => {
  router.push({path: "/orderManagement", query: {teamId: team.teamId}});
};

// 计算到期时间
const getExpireDate = (startTime: string, duration: number) => {
  const start = new Date(startTime);
  start.setFullYear(start.getFullYear() + duration);
  return start.toLocaleDateString();
};

// 跳转到签约首页
const goToSignPage = () => {
  router.push({path: "/contractHomepage"});
};

// 判断按钮是否可用
const isButtonEnabled = (team: any) => {
  // 只有审核通过 + 未签约或待付款才可用
  return team.auditState === 1 && (team.contractState === 0 || team.contractState === 2);
};

// 获取按钮显示文本
const getButtonText = (team: any) => {
  if (team.auditState === 0 && team.contractState === 0) return "待审核"; // 待审核 + 待签约
  if (team.auditState === 2 && team.contractState === 0) return "审核未通过"; // 审核未通过 + 待签约
  if (team.auditState === 1) {
    if (team.contractState === 0) return "提交订单"; // 审核通过 + 待签约
    if (team.contractState === 1) return "签约完成"; // 审核通过 + 已签约
    if (team.contractState === 2) return "去付款"; // 审核通过 + 待付款
  }
  return "";
};

// 按钮点击统一处理
const handleButtonClick = (team: any) => {
  if (!isButtonEnabled(team)) return; // 不可用直接返回
  if (team.contractState === 0) {
    handleSign(team); // 提交订单
  } else if (team.contractState === 2) {
    goToOrderPage(team); // 去付款
  }
};

onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="pending-teams-page">
    <Banner :title="bannerTitle" @search="handleBannerSearch"/>

    <!-- 分页组件 -->
    <div class="pagination-container" style="margin-top: 20px; text-align: center;">
      <el-pagination
          v-if="pendingTeams.length"
          background
          layout="prev, pager, next, sizes"
          :total="total"
          :page-size="queryParams.pageSize"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 15, 20, 25]"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
      />
    </div>

    <!-- 卡片列表 -->
    <div class="teams-list" v-if="pendingTeams.length">
      <div
          v-for="(team, index) in pendingTeams"
          :key="index"
          class="team-item"
      >
        <el-card class="team-card" shadow="hover">
          <div class="team-content">
            <!-- 团队标题和审核状态 -->
            <div class="team-header">
              <h3 class="team-name">{{ team.teamName }}</h3>
              <div class="tags">
                <el-tag v-if="team.auditState === 0" type="info" size="small">待审核</el-tag>
                <el-tag v-else-if="team.auditState === 1" type="success" size="small">审核通过</el-tag>
                <el-tag v-else type="danger" size="small">审核未通过</el-tag>

                <el-tag v-if="team.contractState === 0" type="info" size="small">待签约</el-tag>
                <el-tag v-else-if="team.contractState === 1" type="success" size="small">已签约</el-tag>
                <el-tag v-else type="warning" size="small">待付款</el-tag>
              </div>
            </div>

            <!-- 团队内容 -->
            <div class="team-info">
              <img v-if="team.teamImg" :src="$urlImage + team.teamImg" alt="团队图片" class="team-img"/>
              <p class="team-description">{{ team.teamInfo }}</p>
              <p>签约时长：{{ team.contractDuration }} 年</p>
              <p>签约时间：{{ new Date(team.contractTime).toLocaleDateString() }}</p>
              <p>到期时间：{{ getExpireDate(team.contractTime, team.contractDuration) }}</p>
            </div>

            <!-- 底部操作按钮 -->
            <div class="team-footer">
              <div class="team-price">￥{{ team.teamPrice * team.contractDuration }}</div>
              <el-button
                  type="primary"
                  size="small"
                  :disabled="!isButtonEnabled(team)"
                  @click="handleButtonClick(team)"
              >
                {{ getButtonText(team) }}
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 数据为空时显示 -->
    <div class="empty-container" v-else>
      <p class="empty-text">暂无签约记录</p>
      <el-button type="primary" @click="goToSignPage">去签约</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.pending-teams-page {
  padding: 20px;
}

.teams-list {
  display: grid;
  grid-template-columns: repeat(5, minmax(200px, 1fr));
  gap: 20px;
  padding: 20px;
}

.team-item {
  .team-card {
    width: 100%;
    border-radius: 8px;

    .team-content {
      display: flex;
      flex-direction: column;

      .team-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .team-name {
          margin: 0;
          font-size: 16.2px;
          font-weight: 600;
          color: #303133;
          max-width: calc(100% - 120px);
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          flex-shrink: 1;
        }

        .tags {
          display: flex;
          gap: 6px;
          flex-wrap: nowrap;
          flex-shrink: 0;
        }

        :deep(.el-tag) {
          font-size: 14px;
          padding: 4px 8px;
          height: auto;
          border-radius: 6px;
          white-space: nowrap;
        }
      }

      .team-info {
        margin-bottom: 15px;

        .team-img {
          width: 100%;
          height: auto;
          max-height: 200px;
          object-fit: contain;
          border-radius: 6px;
          margin-bottom: 10px;
        }

        .team-description {
          color: #909399;
          font-size: 14px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          margin: 6px 0;
        }

        p {
          margin: 6px 0;
          font-size: 14px;
          color: #606266;
        }
      }

      .team-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .team-price {
          font-size: 18px;
          font-weight: bold;
          color: #e6a23c;
        }
      }
    }
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 60px;
}

.empty-text {
  font-size: 16px;
  color: #909399;
  margin-bottom: 20px;
}

/* 响应式适配 */
@media screen and (max-width: 1280px) {
  .teams-list {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
  .team-name {
    font-size: 16px;
  }
  :deep(.el-tag) {
    font-size: 14px;
  }
}

@media screen and (max-width: 768px) {
  .teams-list {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 15px;
    padding: 10px;
  }
  .team-name {
    font-size: 14px;
  }
  .team-description, p {
    font-size: 12px;
  }
  .team-price {
    font-size: 16px;
  }
}

@media screen and (max-width: 1440px) {
  .teams-list {
    grid-template-columns: repeat(5, minmax(210px, 1fr));
    gap: 18px;
  }
  .team-name {
    font-size: 16.2px;
  }
  .team-footer {
    font-size: 16px;
  }
  .team-price {
    font-size: 17px;
  }
  :deep(.el-tag) {
    font-size: 15px;
    padding: 4px 8px;
  }
}
</style>
